package xyz.chenyongpeng.userconsumerdubbo.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xyz.chenyongpeng.userconsumerdubbo.service.UserService;
import xyz.chenyongpeng.userconsumerdubbo.vo.LoginVo;
import xyz.chenyongpeng.userconsumerdubbo.vo.WechatVo;
import xyz.chenyongpeng.utils.R;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("Wechat")
public class WechatController {

    @Autowired
    private UserService userService;

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.appsecret}")
    private String appsecret;

    @Value("${wechat.grant_type}")
    private String grant_type;

    @PostMapping("getOpenid")
    public R getOpenid(@RequestParam(name = "code",required = true) String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code="+code+"&grant_type="+grant_type;
        String result = HttpUtil.get(url);

        WechatVo wechatVo = JSONUtil.toBean(result, WechatVo.class);

        if (wechatVo.getErrcode() == -1){
            return R.error(-1, "系统繁忙，此时请开发者稍候再试");
        }else if (wechatVo.getErrcode() == 4029){
            return R.error(-1, "code 无效");
        }else if (wechatVo.getErrcode() == 45011){
            return R.error(45011, "频率限制，每个用户每分钟100次");
        }else if (wechatVo.getErrcode() == 40163){
            return R.error(40163, "code 已被使用过");
        }

        LoginVo vo = null;

        String openid = wechatVo.getOpenid();

        String u_id = userService.saveOrUpdate(openid,null,null,null,null);
        vo = new LoginVo(wechatVo.getSession_key(),wechatVo.getOpenid(),Integer.parseInt(u_id));

        Map<String,Object> map = new HashMap<>();
        map.put("data", vo);
        return R.ok(map);
    }
}
